import axios from 'axios'

const baseURL = 'http://localhost:8123/api'

const apiClient = axios.create({
  baseURL,
  timeout: 60000,
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  }
})

export const createLoveMasterChat = (message, chatId) => {
  const url = `/ai/love_app/chat/sse?message=${encodeURIComponent(message)}&chatId=${encodeURIComponent(chatId)}`
  console.log(`创建LoveMasterChat SSE连接: ${baseURL + url}`)
  try {
    return new EventSource(baseURL + url)
  } catch (error) {
    console.error('创建LoveMaster SSE连接失败:', error)
    return null
  }
}

// 添加编程大师的API函数
export const createCodeMasterChat = (message, chatId) => {
  // 添加type=code参数表明这是编程大师的请求，让后端知道需要返回格式化的代码
  const url = `/ai/love_app/chat/sse?message=${encodeURIComponent(message)}&chatId=${encodeURIComponent(chatId)}&type=code`
  console.log(`创建CodeMasterChat SSE连接: ${baseURL + url}`)
  try {
    return new EventSource(baseURL + url)
  } catch (error) {
    console.error('创建CodeMaster SSE连接失败:', error)
    return null
  }
}

export const createSuperAgentChat = (message) => {
  // 确保消息不为空
  if (!message || message.trim() === '') {
    console.error('createSuperAgentChat: 消息不能为空')
    return null
  }

  console.log('创建SuperAgentChat连接, 消息:', message.substring(0, 30) + (message.length > 30 ? '...' : ''))
  
  // 只保留时间戳参数，确保每次请求不会被缓存
  const url = `/ai/manus/chat?message=${encodeURIComponent(message)}&t=${Date.now()}`
  console.log(`SSE连接URL: ${baseURL + url}`)
  
  try {
    const eventSource = new EventSource(baseURL + url)
    
    // 设置自定义属性
    eventSource.isManualClose = false
    eventSource.lastMessage = message
    eventSource.requestId = Date.now().toString() + Math.random().toString(36).substring(2, 10)
    
    // 重写原生的close方法以便跟踪手动关闭
    const originalClose = eventSource.close
    eventSource.close = function() {
      console.log(`关闭SSE连接 [${this.requestId}]`)
      this.isManualClose = true
      originalClose.call(this)
    }
    
    return eventSource
  } catch (error) {
    console.error('创建SuperAgent SSE连接失败:', error)
    return null
  }
}

export default apiClient 